/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net;

import java.io.IOException;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Session class.
 * 
 */
abstract class Session {

    /** Session state. */
    AtomicBoolean isClosed = new AtomicBoolean(false);

    /** Selector handler to be used by the session. */
    SelectorHandler selectorHandler;

    /** Service. */
    Service service;

    /**
     * Constructor.
     * 
     * @param service Service
     * @param selectorHandler Selector handler
     */
    Session(Service service, SelectorHandler selectorHandler) {
    	this.service = service;
    	this.selectorHandler = selectorHandler;
    }
    
    /**
     * Get the state (closed or not) of the session.
     * 
     * @return "true" if closed, "false" if not closed
     */
    boolean isClosed() {
    	return isClosed.get();
    }

    /**
     * Close the session.
     * 
     * @return "false" if already closed, "true" if had not been closed but has now been closed
     */
    boolean closeSession() {
        if (isClosed.getAndSet(true)) return false;
        try {
            doClose();
        } catch (Exception e) {}
        return true;
    }

    /**
     * Session close processing.
     * 
     * @throws IOException
     */
    abstract void doClose() throws IOException;

    /**
     * Get bound local host address.
     * 
     * @return Local host address
     */
    abstract SocketAddress getLocalAddress();
}
